import axios from 'axios'

// 根据环境决定 baseURL：
// - 生产：使用公开域名 https://api.cumrbull.com.sg
// - 开发：保持相对路径，由 Vite 代理到本地后端
const isProd = typeof window !== 'undefined' && window.location && window.location.hostname.endsWith('cumrbull.com.sg')
const defaultBaseURL = isProd ? 'https://api.cumrbull.com.sg/api' : '/api'

const api = axios.create({
  baseURL: defaultBaseURL,
  withCredentials: true,
  timeout: 15000
})

api.interceptors.request.use(
  (config) => {
    const token = (typeof window !== 'undefined' && window.localStorage)
      ? (localStorage.getItem('admin_token') || localStorage.getItem('token'))
      : null
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    // 为GET请求添加防缓存参数与请求头，避免304
    if ((config.method || 'get').toLowerCase() === 'get') {
      const ts = Date.now()
      config.params = { ...(config.params || {}), _t: ts }
      config.headers['Cache-Control'] = 'no-cache'
      config.headers['Pragma'] = 'no-cache'
      config.headers['If-Modified-Since'] = '0'
    }
    return config
  },
  (error) => Promise.reject(error)
)

api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response && error.response.status === 401) {
      try {
        localStorage.removeItem('admin_token')
        localStorage.removeItem('token')
      } catch (e) {
        // 静默处理本地存储清除失败
      }
      // 可在此触发跳转登录
    }
    return Promise.reject(error)
  }
)

// 认证相关 API
export const authAPI = {
  login: (credentials) => api.post('/auth/login', credentials),
  logout: () => api.post('/auth/logout'),
  getCurrentUser: () => api.get('/auth/me'),
  checkAdminAccess: () => api.get('/admin/system/info')
}

// 仪表板相关 API
export const dashboardAPI = {
  getStats: (timeRange = '7d') => api.get(`/admin/dashboard/stats?timeRange=${timeRange}`),
  getRealtimeData: () => api.get('/admin/dashboard/realtime')
}

// 用户管理 API
export const userAPI = {
  getUsers: (params) => api.get('/admin/users', { params }),
  getUserById: (id) => api.get(`/admin/users/${id}`),
  updateUserStatus: (id, data) => api.put(`/admin/users/${id}/status`, data),
  deleteUser: (id) => api.delete(`/admin/users/${id}`),
  getUserStatistics: () => api.get('/admin/users/statistics')
}

// 菜单管理 API
export const menuAPI = {
  getCategories: (params) => api.get('/admin/menu/categories', { params }),
  createCategory: (data) => api.post('/admin/menu/categories', data),
  updateCategory: (id, data) => api.put(`/admin/menu/categories/${id}`, data),
  deleteCategory: (id) => api.delete(`/admin/menu/categories/${id}`),
  getMenuItems: (params) => api.get('/admin/menu/items', { params }),
  createMenuItem: (data) => api.post('/admin/menu/items', data),
  updateMenuItem: (id, data) => api.put(`/admin/menu/items/${id}`, data),
  deleteMenuItem: (id) => api.delete(`/admin/menu/items/${id}`),
  updateAvailability: (id, data) => api.put(`/admin/menu/items/${id}/availability`, data),
  uploadItemImage: (id, file) => {
    const form = new FormData()
    form.append('image', file)
    return api.post(`/admin/menu/items/${id}/image`, form, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },
  uploadMenuImages: (files) => {
    const form = new FormData()
    files.forEach((f) => form.append('images', f))
    return api.post('/admin/menu/images/batch', form, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },
  // Excel导入导出功能
  downloadTemplate: () => api.get('/admin/menu-import/template/menu.xlsx', { responseType: 'blob' }),
  exportMenu: (params) => api.get('/admin/menu-import/export/menu', { params, responseType: 'blob' }),
  importMenu: (file) => {
    const form = new FormData()
    form.append('file', file)
    return api.post('/admin/menu-import/import/menu', form, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },
  commitImport: (jobId) => api.post('/admin/menu-import/import/menu/commit', { job_id: jobId }),
  getImportJobs: (params) => api.get('/admin/menu-import/import/jobs', { params }),
  getJobStatus: (jobId) => api.get(`/admin/menu-import/import/job/${jobId}`),
  downloadErrors: (jobId) => api.get(`/admin/menu-import/import/errors/${jobId}`, { responseType: 'blob' })
}

// 订单管理 API
export const orderAPI = {
  // 调整为通用订单路由（由路由自身进行管理员鉴权），避免某些环境下 /api/admin 未挂载导致的404
  getOrders: (params) => api.get('/orders/admin/all', { params }),
  getOrderById: (id) => api.get(`/orders/${id}`),
  updateOrderStatus: (id, data) => api.put(`/orders/${id}/status`, data),
  getOrderStatistics: (params) => api.get('/orders/stats', { params }),
  getPopularItems: (params) => api.get('/orders/popular-items', { params }),
  getCategorySales: (params) => api.get('/orders/categories', { params }),
  getOrderTypeDistribution: (params) => api.get('/orders/type-distribution', { params }),
  getPaymentMethodDistribution: (params) => api.get('/orders/payment-distribution', { params }),
  getTopCustomers: (params) => api.get('/orders/top-customers', { params }),
  // 新增：趋势接口
  getOrderTypeTrend: (params) => api.get('/orders/trends', { params }),
  getPaymentMethodTrend: (params) => api.get('/orders/payment-trend', { params })
}

// 优惠券管理 API（保留原实现，供 Coupons 页面使用）
export const couponAPI = {
  getCoupons: (params) => api.get('/admin/coupons', { params }),
  createCoupon: (data) => api.post('/admin/coupons', data),
  updateCoupon: (id, data) => api.put(`/admin/coupons/${id}`, data),
  deleteCoupon: (id) => api.delete(`/admin/coupons/${id}`),
  batchDistribute: (data) => api.post('/admin/coupons/batch-distribute', data),
  getCouponStatistics: () => api.get('/admin/coupons/statistics')
}

// 系统管理 API
export const systemAPI = {
  getSystemInfo: () => api.get('/admin/system/info'),
  getSystemLogs: (params) => api.get('/admin/system/logs', { params }),
  clearCache: () => api.post('/admin/system/clear-cache')
}

// 报表管理 API
export const reportAPI = {
  // 获取报表列表
  getReportList: () => api.get('/reports'),
  
  // 获取报表配置
  getReportConfig: (reportKey) => api.get(`/reports/config/${reportKey}`),
  
  // 财务类报表
  getCashDeclarationReport: (filters) => api.post('/reports/financial/cash-declaration', filters),
  getDailyCollectionReport: (filters) => api.post('/reports/financial/daily-collection', filters),
  getPaymentReport: (filters) => api.post('/reports/financial/payment-report', filters),
  getProfitAnalysisReport: (filters) => api.post('/reports/financial/profit-analysis', filters),
  
  // 销售类报表
  getDailySalesSummaryReport: (filters) => api.post('/reports/sales/daily-summary', filters),
  getHourlyAnalysisReport: (filters) => api.post('/reports/sales/hourly-analysis', filters),
  getHourlyOverviewReport: (filters) => api.post('/reports/sales/hourly-overview', filters),
  getSalesAndCountReport: (filters) => api.post('/reports/sales/sales-and-count', filters),
  
  // 商品类报表
  getProductSalesReport: (filters) => api.post('/reports/product/sales-report', filters),
  getProductAnalysisReport: (filters) => api.post('/reports/product/analysis-report', filters),
  getProductReturnReport: (filters) => api.post('/reports/product/return-report', filters),
  getCondimentsReport: (filters) => api.post('/reports/product/condiments-report', filters),
  getDiscountReport: (filters) => api.post('/reports/product/discount-report', filters),
  
  // 顾客与服务类报表
  getRatingReport: (filters) => api.post('/reports/customer/rating-report', filters),
  getReceiptJournalReport: (filters) => api.post('/reports/customer/receipt-journal', filters),
  getHourlyItemReport: (filters) => api.post('/reports/customer/hourly-item-report', filters),
  getPaymentProductReport: (filters) => api.post('/reports/customer/payment-product-report', filters),
  
  // 导出功能
  exportReport: (reportKey, format, filters) => api.post(`/reports/export/${reportKey}`, { format, filters }),
  getExportStatus: (exportId) => api.get(`/reports/export/status/${exportId}`),
  downloadExportFile: (exportId) => api.get(`/reports/export/download/${exportId}`, { responseType: 'blob' }),
  
  // 权限管理
  getReportPermissions: () => api.get('/reports/permissions'),
  updateReportPermissions: (role, reportKey, permissions) => api.put('/reports/permissions', { role, reportKey, permissions }),
  
  // 订阅管理
  getReportSubscriptions: () => api.get('/reports/subscriptions'),
  createReportSubscription: (data) => api.post('/reports/subscriptions', data),
  updateReportSubscription: (subscriptionId, data) => api.put(`/reports/subscriptions/${subscriptionId}`, data),
  deleteReportSubscription: (subscriptionId) => api.delete(`/reports/subscriptions/${subscriptionId}`)
}

// 邀请管理 API
export const inviteAPI = {
  getInviteRecords: (params) => api.get('/invites/records', { params }),
  getInviteStats: () => api.get('/invites/stats'),
  generateInviteCode: () => api.post('/invites/generate'),
  issueCoupon: (id, data) => api.post(`/invites/issue-coupon/${id}`, data),
  getMyInvites: (params) => api.get('/invites/my-invites', { params }),
  getMyStats: () => api.get('/invites/my-stats')
}

export default api